package JUC.轮流打印1_100;

public class AlternatePriting {
    private int currentNum = 1;
    private static final Object lock = new Object();

    public static void main(String[] args) {
        AlternatePriting al = new AlternatePriting();
        new Thread(() -> al.printNum(true)).start();
        new Thread(() -> al.printNum(false)).start();
    }

    private void printNum(boolean isOdd) {
        while (currentNum <= 100) {
            synchronized (lock) {//syn的作用是同步
                //被阻塞
                while ((isOdd && currentNum % 2 == 0) || (!isOdd && currentNum % 2 != 0)) {
                    //如果是奇数线程而且现在是奇数，不会阻塞；
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (currentNum <= 100) {
                    System.out.println("Thread" + (isOdd ? "Odd" : "Even") + ":" + currentNum);
                    currentNum++;
                    lock.notifyAll();
                }
            }
        }
    }

}
